package com.hbsoft.handler;

import com.hbsoft.annotation.WeChatRequired;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class WeChatHandlerInterceptor implements HandlerInterceptor {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("过滤器执行++++++++++++++++++++++++++++++++++++++++++++");
        if (HandlerMethod.class.isInstance(handler)) {
            logger.info("过滤器执行++++++++++++++++++++++++++++++++++++++11111111111111111");
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            WeChatRequired weChatR = handlerMethod.getMethod().getAnnotation(WeChatRequired.class);
            if(weChatR != null){
                logger.info("过滤器执行++++++++++++++++++++++++++++++++++++++22222222222222222222");
                String agent = request.getHeader("User-Agent");
                if ((agent == null) || (agent.toLowerCase().indexOf("micromessenger") <= 0)) {
                    response.sendRedirect("weChat");
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
